<!--
 * @Description: 组织结构-列表
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-23
-->
<template>
  <div class="ssc-list org-dept-list">
    <div class="ssc-search">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="名称">
            <a-input v-model:value="searchParam.name" placeholder="请输入组织名称" :maxlength="20" />
          </a-form-item>
        </a-col>
        <a-col :span="18">
          <a-row justify="end">
            <a-button @click="clear()">重置</a-button>
            <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
          </a-row>
        </a-col>
      </a-row>
    </div>
    <div class="ssc-table">
      <div class="ssc-table-header">
        <span class="ssc-table-header-title">组织结构</span>
      </div>
      <a-table v-if="table.initialLoaded" :columns="table.columns" :data-source="table.datas" :defaultExpandedRowKeys="table.expandedRowKeys" :loading="table.loading">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span>
              <a @click="addUnderling(record.deptId)">添加下级</a>
              <template v-if="record.parentId != 0">
                <a-divider type="vertical" />
                <a @click="edit(record)">编辑</a>
                <a-divider type="vertical" />
                <a class="color-error" @click="dele(record.deptId)">删除</a>
              </template>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <div class="modal">
      <Add v-model:visible="modalAdd.visible" :parent-dept-id="modalAdd.deptId" @success="modalAdd.success" />
      <Edit v-model:visible="modalEdit.visible" :dept-id="modalEdit.deptId" :dept-name="modalEdit.deptName" @success="modalEdit.success" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { message, Modal, type TreeProps } from 'ant-design-vue'
  import { TreeDataItem } from 'ant-design-vue/lib/tree/Tree'
  import { computed, onMounted, reactive } from 'vue'

  import { requestDeleteDept, requestGetDeptList } from '/@/api/business/company/dept'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getCompanyInfo } from '/@/storage'

  import Add from './components/Add.vue'
  import Edit from './components/Edit.vue'

  const { companyId } = getCompanyInfo()

  /** 搜索条件 */
  const searchParam = reactive({ name: '' })

  /** 表格配置 */
  const table = reactive({
    columns: [
      { title: '名称', dataIndex: 'deptName', key: 'deptName' },
      { title: '权重', dataIndex: 'orderNum' },
      { title: '创建人', dataIndex: 'createName', customRender: ({ record }) => record.createName || '--' },
      { title: '创建时间', dataIndex: 'createTime' },
      { title: '操作', key: 'action' },
    ],
    datas: [] as TreeProps['treeData'],
    initialLoaded: false,
    loading: false,
    expandedRowKeys: computed(() => [(table.datas as TreeDataItem[])[0]?.key.toString()]),
  })

  onMounted(() => initData())

  /**
   * 初始化数据
   */
  const initData = async () => {
    table.loading = true
    const { responseData } = await requestGetDeptList({ companyId, deptName: searchParam.name })
    table.datas = responseData.map((item: GetDeptListTypes.IResponse) => deepDept(item))
    table.loading = false
    table.initialLoaded = true
  }

  /**
   * 递归获取部门数据
   * dept 部门
   */
  const deepDept = (dept: GetDeptListTypes.IResponse) => {
    return {
      ...dept,
      key: dept.deptId.toString(),
      children: dept.children.length === 0 ? undefined : dept.children.map((child: GetDeptListTypes.IResponse) => deepDept(child)),
    }
  }

  /**
   * 重置
   */
  const clear = () => (searchParam.name = '')

  /**
   * 搜索
   */
  const search = () => initData()

  /** 添加下级弹窗 */
  const modalAdd = reactive({
    visible: false,
    deptId: NaN,
    success: () => initData(),
  })

  /**
   * 添加下级
   * @param deptId 部门id
   */
  const addUnderling = (deptId: number) => {
    modalAdd.visible = true
    modalAdd.deptId = deptId
  }

  /** 编辑弹窗 */
  const modalEdit = reactive({
    visible: false,
    deptId: NaN,
    deptName: '',
    success: () => initData(),
  })

  /**
   * 编辑
   * @param record 部门
   */
  const edit = (record: GetDeptListTypes.IResponse) => {
    modalEdit.visible = true
    modalEdit.deptId = record.deptId
    modalEdit.deptName = record.deptName
  }

  /**
   * 删除
   * @param deptId 部门id
   */
  const dele = (deptId: number) => {
    Modal.confirm({
      title: '删除',
      content: '删除当前部门，需确定部门下没有人员。如果有对应的人员，请在「组织人员」中进行移除。',
      okText: '确定删除',
      onOk: async () => {
        const { responseCode } = await requestDeleteDept({ deptId })
        if (responseCode === HttpCodeEnum.SUCCESS) {
          message.success('删除成功')
          initData()
        }
      },
    })
  }
</script>

<style lang="less" scoped>
  .color-error {
    color: @error-color;
  }
</style>
